package com.whisperarts.financer.app.actions;

import java.util.Arrays;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import com.whisperarts.financer.app.Application;
import com.whisperarts.financer.app.dialogs.AddAccountDialog;
import com.whisperarts.financer.app.utils.UIUtils;
import com.whisperarts.financer.dao.AccountsDAO;
import com.whisperarts.financer.model.account.Account;
import com.whisperarts.financer.model.account.AccountsCategory;

public class AddAccountAction extends Action implements 
	ISelectionListener, IWorkbenchAction {
	
	private final IWorkbenchWindow window;
	public final static String ID = "com.whisperarts.financer.app.actions.addAccount";
	private IStructuredSelection selection;
	
	
	public AddAccountAction(IWorkbenchWindow window) {
		this.window = window;
		setId(ID);
		setText("&Add Account");
		setToolTipText("Add an account to current accounts list");
		setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(Application.PLUGIN_ID, ISharedImages.IMG_OBJ_ADD));
		window.getSelectionService().addSelectionListener(this);
	}
	
	@Override
	public void selectionChanged(IWorkbenchPart part, ISelection incoming) {
		if (incoming instanceof IStructuredSelection) {
			selection = (IStructuredSelection) incoming;
			setEnabled(selection.size() == 1 &&
					selection.getFirstElement() instanceof AccountsCategory);
		} else {
			setEnabled(false);
		}
	}
	
	@Override
	public void dispose() {
		window.getSelectionService().removeSelectionListener(this);
	}
	
	@Override
	public void run() {
		AddAccountDialog dialog = new AddAccountDialog(window.getShell(), getAccountType());
		if (dialog.open() == Window.OK) {
			Account account = dialog.getAccount();
			if (AccountsDAO.saveAccount(account) == 0) {
				AccountsCategory category = AccountsDAO.getAccountsCategories()[account.getAccountType()];
				category.getAccounts().add(account);			
				UIUtils.refreshNode(category);				
			}
		}
	}

	private int getAccountType() {		
		return Arrays.asList( AccountsDAO.getAccountsCategories() ).indexOf(selection.getFirstElement());
	}
}
